package com.itjiange.springbootinit.bizmq;

import com.itjiange.springbootinit.common.ErrorCode;
import com.itjiange.springbootinit.constant.ChartConstant;
import com.itjiange.springbootinit.constant.MqConstant;
import com.itjiange.springbootinit.exception.BusinessException;
import com.itjiange.springbootinit.model.dto.ai.ChatResponse;
import com.itjiange.springbootinit.model.entity.Chart;
import com.itjiange.springbootinit.service.ChartService;
import com.itjiange.springbootinit.utils.ChartAIUtils;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author 15117
 * @data 2023/12/29 9:40
 */
@Component
@Slf4j
public class MyBIMessageConsumer {

    @Resource
    private ChartService chartService;

    /**
     * 接收到受监听队列的消息
     * @param message 消息
     * @param channel 消息频道
     * @param deliveryTag 表示消息的唯一标识符
     */
    @SneakyThrows
    @RabbitListener(queues = {MqConstant.QUEUE_NAME}, ackMode = "MANUAL")
    public void receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        log.info("Received message: {}", message);

        // 校验
        if (StringUtils.isBlank(message)) {
            channel.basicNack(deliveryTag, false, true);
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 图表id
        long chartId = Long.parseLong(message);

        // 从数据库中获取图表信息
        Chart chart = chartService.getById(chartId);

        // 将图表状态改为执行中
        Chart updateChart = new Chart();
        updateChart.setId(chart.getId());
        updateChart.setStatus(ChartConstant.CHAT_STATE_RUNNING);
        boolean flag = chartService.updateById(updateChart);
        if (!flag) {
            handleChartError(chart.getId(), "图表状态修改失败");
            return;
        }
        // 用户输入语句
        StringBuilder userInput = new StringBuilder();
        userInput.append("分析需求：").append(chart.getGoal());
        userInput.append("原始数据：")
                .append('\n')
                .append(chart.getGenChart());
        if (StringUtils.isNotBlank(chart.getChartType())) {
            userInput.append("生成").append(chart.getChartType());
        }
        ChatResponse chat = ChartAIUtils.chat(userInput.toString());
        // 校验
        String outputText = chat.getOutput().text;
        if (StringUtils.isBlank(outputText)) {
            handleChartError(chart.getId(), "AI 无响应");
            return;
        }
        // 解析 AI 返回结果
        String[] split = outputText.split("【【【】】】");
        if (split.length > 3) {
            handleChartError(chart.getId(), "AI 图表生成失败");
            return;
        }
        String genChart = split[1].trim();
        String genResult = split[2].trim();
        Chart updateChartResult = new Chart();
        updateChartResult.setId(chart.getId());
        updateChartResult.setGenChart(genChart);
        updateChartResult.setGenResult(genResult);
        updateChartResult.setStatus(ChartConstant.CHAT_STATE_SUCCEED);
        boolean resFlag = chartService.updateById(updateChartResult);
        if (!resFlag) {
            handleChartError(chart.getId(), "图表成功状态更新失败");
        }

        // 表示消息不是持久化
        channel.basicAck(deliveryTag, false);
    }

    /**
     * 执行失败
     * @param id
     * @param execMessage
     */
    private void handleChartError(Long id, String execMessage) {
        // 更改图表状态为失败
        Chart updateChart = new Chart();
        updateChart.setId(id);
        updateChart.setStatus(ChartConstant.CHAT_STATE_FAILED);
        updateChart.setExecMessage(execMessage);
        boolean flag = chartService.updateById(updateChart);
        if (!flag) {
            log.info("图表：" + id + "，执行失败，execMessage：" + execMessage);
        }
    }
}
